#region

using Microsoft.AspNetCore.Http;

using UAParser;

#endregion

namespace Leo.Core.Util
{
    public static class HttpContextExtension
    {
        /// <summary>
        ///     获取浏览器信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string? GetBrowserInfo(this HttpContext context)
        {
            var headers = context.Request.Headers;
            if (headers.ContainsKey("User-Agent"))
            {
                var clientInfo = Parser.GetDefault().Parse(headers["User-Agent"]);
                var browser = clientInfo?.UA.Family + clientInfo?.UA.Major;
                var os = clientInfo?.OS.Family + clientInfo?.OS.Major;
                return $"{browser} ({os})";
            }

            return "unkown";
        }

        /// <summary>
        ///     获取请求的ip4
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string? GetRequestIPv4(this HttpContext context)
        {
            string? ip = string.Empty;
            var ipAddress = context.Connection.RemoteIpAddress;
            if (ipAddress != null)
            {
                var headers = context.Request.Headers;
                if (headers.ContainsKey("X-Real-IP"))
                {
                    ip = headers["X-Real-IP"].FirstOrDefault();
                }

                if (context.Request.Headers.ContainsKey("X-Forwarded-For"))
                {
                    ip = headers["X-Forwarded-For"].FirstOrDefault();
                }

                if (string.IsNullOrEmpty(ip))
                {
                    ip = ipAddress?.MapToIPv4()?.ToString();
                }
            }

            return ip;
        }

        /// <summary>
        ///     获取根地址
        /// </summary>
        /// <param name="request"></param>
        /// <param name="path">附加路径</param>
        /// <returns></returns>
        public static string GetHost(this HttpRequest request, string path = null)
        {
            return $"{request.Scheme}://{request.Host}{request.PathBase}{path ?? string.Empty}";
        }
    }
}